import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:reorderable_grid_view/reorderable_grid_view.dart';

class ImageSelector extends StatefulWidget {
  final List<String>? imagePaths;
  bool? readOnly;
  final int? max;
  ImageSelector({super.key, this.imagePaths, this.readOnly = false, this.max = 9});

  @override
  State<ImageSelector> createState() => _SelectorImageState();
}

class _SelectorImageState extends State<ImageSelector> {
  final List<String> imagePaths = [];
  late Offset dragPosition;
  bool isInTrashCan = false; // 标记是否在垃圾桶区域
  bool isDragging = false; // 标记当前是否正在拖拽
  Color trashCanColor = Colors.red.withOpacity(0.7); // 初始垃圾桶的颜色
  IconData trashCanIcon = Icons.delete_outline; // 初始垃圾桶图标
  final String addButtonKey = 'add_button'; // 为添加按钮分配特殊的 key

  @override
  void initState() {
    imagePaths.addAll(widget.imagePaths ?? []);
    super.initState();
  }

  // 删除图片的方法
  void _removeImage(int index) {
    imagePaths.removeAt(index);
    setState(() {});
  }

  // 添加图片的方法（模拟图片添加）
  void _addImage() {
    imagePaths.add('https://img2.baidu.com/it/u=446981511,947966320&fm=253&fmt=auto&app=120&f=JPEG?w=750&h=500'); // 示例占位图
    setState(() {});
  }

  // 判断拖拽图片是否在垃圾桶区域
  bool _isOverTrashCan(Offset position) {
    final trashCanRect = Rect.fromLTWH(
      0,
      MediaQuery.of(context).size.height - 88,
      MediaQuery.of(context).size.width,
      88,
    );
    return trashCanRect.contains(position);
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          padding: const EdgeInsets.all(8),
          child: ReorderableGridView.count(
            crossAxisCount: 3,
            crossAxisSpacing: 4,
            mainAxisSpacing: 4,
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            padding: const EdgeInsets.fromLTRB(2, 2, 2, 2),
            onReorder: (int oldIndex, int newIndex) {
              // 如果是添加按钮，则不处理拖拽逻辑
              if (imagePaths.length < widget.max! && oldIndex == imagePaths.length) {
                return;
              }
              isDragging = false; // 拖拽结束时重置状态
              setState(() {
                if (newIndex > oldIndex) {
                  newIndex -= 1;
                }
                final item = imagePaths.removeAt(oldIndex);
                imagePaths.insert(newIndex, item);

                // 拖拽结束时检查是否在垃圾桶区域，如果在则删除图片
                if (_isOverTrashCan(dragPosition)) {
                  _removeImage(newIndex);
                }
                isDragging = false; // 重置拖拽状态
                trashCanIcon = Icons.delete_outline; // 重置垃圾桶图标
                trashCanColor = Colors.red.withOpacity(0.7); // 重置垃圾桶颜色
              });
            },
            onDragStart: (index) {
              // 如果是添加按钮，则不显示垃圾桶按钮
              if (imagePaths.length < widget.max! && index == imagePaths.length) {
                return;
              }
              isDragging = true; // 标记为正在拖拽
              trashCanIcon = Icons.delete_outline; // 恢复垃圾桶的默认图标
              trashCanColor = Colors.red.withOpacity(0.7); // 恢复垃圾桶的默认颜色
            },
            onDragUpdate: (dragIndex, position, delta) {
              setState(() {
                dragPosition = position; // 更新拖拽位置
                // 检查是否在垃圾桶区域
                if (_isOverTrashCan(position)) {
                  trashCanColor = Colors.red; // 高亮垃圾桶颜色
                  trashCanIcon = Icons.delete; // 切换为打开盖子的垃圾桶图标
                } else {
                  trashCanIcon = Icons.delete_outline; // 恢复关闭盖子的垃圾桶图标
                  trashCanColor = Colors.red.withOpacity(0.7); // 恢复垃圾桶的默认颜色
                }
              });
            },
            dragWidgetBuilderV2: DragWidgetBuilderV2(
              isScreenshotDragWidget: false,
              builder: (int index, Widget child, ImageProvider? screenshot) {
                return Transform.scale(
                  scale: 1.2,
                  child: child,
                );
              },
            ),
            children: [
              ...List.generate(imagePaths.length, (index) {
                return Image.network(
                  imagePaths[index],
                  fit: BoxFit.cover,
                  key: ValueKey(imagePaths[index]),
                );
              }),
              // 添加按钮，只有在未超过 max 数量时才显示
              if (!widget.readOnly! && imagePaths.length < widget.max!)
                Container(
                  key: ValueKey(addButtonKey), // 特殊 key，避免与图片的 key 冲突
                  color: Colors.grey[200],
                  child: IconButton(
                    icon: const Icon(Icons.add, size: 36, color: Colors.black),
                    onPressed: _addImage,
                  ),
                ),
            ],
          ),
        ),
        if (isDragging) _buildTrashCan(), // 仅在拖拽时显示垃圾桶
      ],
    );
  }

  // 构建添加图片按钮
  Widget _buildAddButton() {
    return GestureDetector(
      onTap: _addImage,
      key: UniqueKey(),
      child: Container(
        color: Colors.grey[200],
        child: const Icon(Icons.add, size: 36, color: Colors.black),
      ),
    );
  }

  // 构建垃圾桶视图
  Widget _buildTrashCan() {
    return Align(
      alignment: Alignment.bottomCenter,
      child: Container(
        height: 88,
        width: double.infinity,
        color: trashCanColor, // 使用动态颜色
        child: Center(
          child: Icon(
            trashCanIcon,
            color: Colors.white,
            size: 36,
          ),
        ),
      ),
    );
  }
}

class ImageSelectorPage extends StatelessWidget {
  const ImageSelectorPage({super.key});

  // 主视图
  Widget _buildView() {
    final images = [
      "https://img1.baidu.com/it/u=2931243091,718249849&fm=253&fmt=auto&app=120&f=JPEG?w=569&h=427",
      "https://img2.baidu.com/it/u=1195773901,4039087122&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=750",
      "https://img0.baidu.com/it/u=2567590042,3251997562&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=623",
      "https://img0.baidu.com/it/u=1643766442,2564576316&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=336",
    ];
    return ImageSelector(imagePaths: images, readOnly: false, max: 9);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("图片选择器"), elevation: 1),
      body: Column(
        children: [
          Expanded(child: _buildView()),
        ],
      ),
    );
  }
}
